//
//  WeatherModel.m
//  GetFit3.0
//
//  Created by 圆圆陈 on 2017/12/25.
//  Copyright © 2017年 lxc. All rights reserved.
//

#import "WeatherModel.h"
#import <QuartzCore/QuartzCore.h>

#define WeatherModelLastUpdatetime @"WeatherModelLastUpdatetime"

@interface WeatherModel ()<CLLocationManagerDelegate>
@property (nonatomic, strong) UIAlertView *alert;
@end

@implementation WeatherModel {
    CLLocationManager *localManager;
    CLGeocoder        *geocoder;
    NSTimer           *weatherTimer;
    NSInteger         failTimes;
}
- (instancetype)init {
    self = [super init];
    if (self) {
        _weatherCode = [NSString string];
        _weatherInfo = [NSString string];
        _weatherName = @"0";
        _maxTem      = @"0";
        _minTem      = @"0";
        _tem         = @"0";
        failTimes    = 0;
        localManager = [[CLLocationManager alloc]init];
        //设置代理
        localManager.delegate = self;
        //设置定位的精度
        [localManager setDesiredAccuracy:kCLLocationAccuracyBest];
        //位置信息更新最小距离
        localManager.distanceFilter = 20;
        if ([UIDevice currentDevice].systemVersion.floatValue >= 9.0) {
            localManager.allowsBackgroundLocationUpdates = YES;
        }
        if ([localManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [localManager requestAlwaysAuthorization];
        }
        geocoder = [[CLGeocoder alloc] init];
    }
    return self;
}

- (void)startUpdateLocation {
    [weatherTimer invalidate];
    weatherTimer = nil;
    NSDate *weatherDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"weatherDate"];
    if ([[NSDate date] timeIntervalSinceDate:weatherDate] > 3600 || weatherDate == nil) {
        [localManager startUpdatingLocation];
    } else {
        if (KK_BLEConnect.isConnected) {
            [KK_BLESend sendTemperature];
        }
    }
    weatherTimer = [NSTimer timerWithTimeInterval:60 target:self selector:@selector(startLocation) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:weatherTimer forMode:NSRunLoopCommonModes];
}

-(void)startUpdateLocationNow
{
     [localManager stopUpdatingLocation];
     [localManager startUpdatingLocation];
}

- (void)startLocation {
    //    NSLog(@"请求一次系统时间");
    NSDate    *date  = [NSDate date];
    NSInteger hour   = date.hour;
    NSInteger min    = date.minute;
    NSInteger second = date.second;
    
    //（00:00 整点开始 0600 1200 1800 0000 整点推天气到手环）
    if (hour%6 == 0) {
        if ((min == 1 && second == 0) || (min == 0 && second <= 59)) {
            [localManager startUpdatingLocation];
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    switch (status) {
        case kCLAuthorizationStatusNotDetermined: {
            NSLog(@"用户还未进行授权");
            LogWrite(@"天气定位", @"用户还未进行授权", nil);
            break;
        }
        case kCLAuthorizationStatusDenied: {
            // 判断当前设备是否支持定位和定位服务是否开启
            if ([CLLocationManager locationServicesEnabled]) {
                [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(alertShow) object:nil];
                [self performSelector:@selector(alertShow) withObject:nil afterDelay:3.0];
            } else {
                NSLog(@"定位服务关闭,弹出系统的提示框,点击设置可以跳转到定位服务界面进行定位服务的开启");
                LogWrite(@"天气定位", @"定位服务关闭", nil);
            }
            break;
        }
        case kCLAuthorizationStatusRestricted: {
            NSLog(@"受限制的");
            LogWrite(@"天气定位", @"受限制的", nil);
            break;
        }
        case kCLAuthorizationStatusAuthorizedAlways: {
            NSLog(@"授权允许在前台和后台均可使用定位服务");
            LogWrite(@"天气定位", @"授权允许在前台和后台均可使用定位服务", nil);
            break;
        }
        case kCLAuthorizationStatusAuthorizedWhenInUse: {
            NSLog(@"授权允许在前台可使用定位服务");
            LogWrite(@"天气定位", @"授权允许在前台可使用定位服务", nil);
            break;
        }
        default:
            break;
    }
}

- (void)alertShow
{
    int time = [WeatherModelLastUpdatetime getIntValue];
    int currentMins = [NSDate getCurrentMinTotal];
    if (time < currentMins) {
        NSLog(@"位置信息获取失败,是否跳转到设置界面");
        LogWrite(@"天气定位", @"用户不允许程序访问位置信息或者手动关闭了位置信息的访问", nil);
        
        _alert = [[UIAlertView alloc] initWithTitle:SN_Text(@"位置信息获取失败,是否跳转到设置界面?")
                                            message:@"" delegate:self
                                  cancelButtonTitle:SN_Text(@"取消")
                                  otherButtonTitles:SN_Text(@"确定"), nil];
        _alert.tag = 2;
        [[UIView appearance] setTintColor:UIColorRGB(72, 72, 72)];
        [_alert show];
        [WeatherModelLastUpdatetime setIntValue:currentMins];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 2) {
        if (buttonIndex == 0) {
        } else {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
            }
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    // 设备的当前位置
    CLLocation *userLocation = [locations lastObject];
    
    [geocoder reverseGeocodeLocation:userLocation completionHandler:^(NSArray<CLPlacemark *> *_Nullable placemarks, NSError *_Nullable error) {
        CLPlacemark *pl = [placemarks firstObject];
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:[NSString stringWithFormat:@"%.3f", userLocation.coordinate.latitude] forKey:@"lat"];
        [dict setObject:[NSString stringWithFormat:@"%.3f", userLocation.coordinate.longitude] forKey:@"lon"];
        if (pl) {
            NSString *str = [NSString stringWithFormat:@"%@%@%@", pl.addressDictionary[@"Country"], pl.addressDictionary[@"State"], pl.addressDictionary[@"City"]];
            [dict setObject:str forKey:@"city"];
            [SAVEWEATHERDIC setObjectValue:dict];
        } else {
            LogWrite(@"天气定位", nil, @"未定位到");
            [SAVEWEATHERDIC setObjectValue:@""];
            return;
        }
        NSLog(@"请求天气为dict>>>>%@",dict);
        
        [SN_Net getWeatherWith:dict Success:^(id responseObject) {
           [localManager stopUpdatingLocation];
            NSArray *array = responseObject[@"data"];
            NSMutableArray *arr = [[NSMutableArray alloc] init];
            for (int k = 0; k <array.count; k ++) {
                NSDictionary *dic = [array objectAtIndex:k];
                SNWeatherModel *model = [SN_USER.weatherArray objectAtIndex:k];
                NSString *dateString = dict[@"date"];
                NSString *weatherInfo = dic[@"cond_txt"];
                NSString *maxTem = dic[@"tmp_max"];
                NSString *minTem = dic[@"tmp_min"];
                NSString *weatherCode = dic[@"cond_code"];
                NSString *tem = dic[@"tmp"];
                model.dateString = dateString;
                if (![weatherInfo isEqual:[NSNull null]]) {
                    model.weatherInfo = weatherInfo;
                }
                if (![maxTem isEqual:[NSNull null]]) {
                    model.maxTem = maxTem;
                }
                if (![minTem isEqual:[NSNull null]]) {
                    model.minTem = minTem;
                }
                if (![weatherCode isEqual:[NSNull null]]) {
                    model.weatherCode = weatherCode;
                }
                
                if (![tem isEqual:[NSNull null]]) {
                    model.tem = tem;
                }
                [arr addObject:dic];
            }
            [SNWEATHERSAVE setObjectValue:arr];
            [SN_PublicClass updateWeather];
            [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"weatherDate"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            LogWrite(@"天气请求", nil, @"成功");
            if (SN_PublicClass.weatherBlock) {
                SN_PublicClass.weatherBlock();
            }
        } fail:^(id object) {
            failTimes++;
            if (failTimes < 1) {
                [localManager stopUpdatingLocation];
                [localManager startUpdatingLocation];
            } else {
                failTimes = 0;
                [localManager stopUpdatingLocation];
            }
            LogWrite(@"天气请求", nil, ([error localizedDescription]));
        }];
    }];
}

//定位失败的回调方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"无法获取当前位置 error : %@", error.localizedDescription);
}

+ (WeatherModel *)getModelFromDBWithKey:(NSString *)key
{
    WeatherModel *model = [WeatherModel searchSingleWithWhere:[NSString stringWithFormat:@"weatherName='%@'",key] orderBy:nil];
    
    if (!model) {
        model = [[WeatherModel alloc] init];
        model.weatherName = key;
        [model saveToDB];
    }
    return model;
}

// 表名
+ (NSString *)getTableName {
    return @"WeatherModel";
}

// 主键
+ (NSString *)getPrimaryKey {
    return @"weatherName";
}

// 表版本
+ (int)getTableVersion {
    return 1;
}

+ (void)initialize {
    [super initialize];
}

@end
